import React from 'react';
import {Spin, message as msg, Popconfirm, Card, Button, Row, Col, Table, Form, message as componentMessage, Modal} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, FIXED_COLUMN_WIDTH, PAGE, PAGINATION_OPTIONS} from '../constants';
import {updateApplyReport, getDetail} from './api';
import {conventEnumValueToString} from '../utils';
import TextArea from 'Shared/components/TextArea';
import DealerResourceListSelectPanel from './DealerResourceListSelectPanel';
import {agentKind} from '../Enum';
import {injectIntl} from './intl';
import ImportPanel from './ImportPanel';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

class UpdatePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showDealerResourceListSelectPanel: false,
        data: {},
        dealerResourceLists: [],
        updateDealerResourceLists: [],
        newDealerResourceLists: [],
        showImportPanel: false,
        lv2: [],
        lv3: [],
        lv4: [],
        isSearch: false,
        detailPagination: {
            pageIndex: PAGE.index,
            pageSize: 100,
            sortedColumnKey: 'code',
            sortedOrder: true,
            ...PAGINATION_OPTIONS
        },
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        dealerResourceLists: res.data.dealerResourceLists,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChangeBrandDetail = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            dealerId: '',
        });
        this.setState({
            hasOperat: true,
            data,
            dealerResourceLists: [],
        });
    }
    onChange = (value, name) => {
        const {dealerResourceLists} = this.state;
        if(this.state.data.brandId !== value && dealerResourceLists.length > 0)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'addPanel.message.switch',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'addPanel.message.brandSwitchDetails',
                    defaultMessage: '变更品牌，将会清空服务站可供资源清单数据，是否清空？'
                }),
                onOk: () => this.onChangeBrandDetail(value, name)
            });
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, updateDealerResourceLists} = this.state;
        const dealerResourceLists = this.state.dealerResourceLists;
        const {isDealerUser} = this.props;
        const isValid = newOrUpdateOrderValidator(data, dealerResourceLists, isDealerUser);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            dealerId: data.id,
            rowVersion: data.rowVersion,
            dealerResourceLists: updateDealerResourceLists.map(v => ({
                isUpdate: v.isUpdate,
                id: v.id,
                productCode: v.productCode,
                productName: v.productName
            }))
        };

        this.setState({loading: true});
        updateApplyReport(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    // 增加清单
    onClickAddDetailBtn = () => {
        if(!this.state.data.brandId)
            return componentMessage.warning(this.props.intl.formatMessage({
                id: 'updatePanel.validate.brandRequired',
                defaultMessage: '请先选择品牌'
            }));
        this.setState({
            showDealerResourceListSelectPanel: !this.state.showDealerResourceListSelectPanel
        });
    }
    // 导入清单
    onClickImportBtn = () => {
        this.setState({showImportPanel: true});
    }
    onCloseImportPanel = () => {
        this.setState({showImportPanel: false});
    }
    onImportChange = records => {
        const {data, updateDealerResourceLists} = this.state;
        if(records.payload) {
            const dealerResourceLists = this.state.dealerResourceLists || [];
            records.payload.content.forEach(r => {
                const index = dealerResourceLists.findIndex(v => v.id === r.id);
                if(index === -1) {
                    updateDealerResourceLists.push({
                        brandId: data.brandId,
                        id: r.id,
                        lV1Code: r.lV1Code,
                        lV1Name: r.lV1Name,
                        lV2Code: r.lV2Code,
                        lV2Name: r.lV2Name,
                        lV3Code: r.lV3Code,
                        lV3Name: r.lV3Name,
                        lV4Code: r.lV4Code,
                        lV4Name: r.lV4Name,
                        productCode: r.lv5Code,
                        productName: r.lv5Name,
                        isUpdate: true
                    });
                    dealerResourceLists.push({
                        brandId: data.brandId,
                        id: r.id,
                        lV1Code: r.lV1Code,
                        lV1Name: r.lV1Name,
                        lV2Code: r.lV2Code,
                        lV2Name: r.lV2Name,
                        lV3Code: r.lV3Code,
                        lV3Name: r.lV3Name,
                        lV4Code: r.lV4Code,
                        lV4Name: r.lV4Name,
                        productCode: r.lv5Code,
                        productName: r.lv5Name,
                        isUpdate: true
                    });
                }
            });
            this.setState({
                dealerResourceLists: [...dealerResourceLists],
                hasOperat: true,
                updateDealerResourceLists,
                showImportPanel: false,
                isAlert: true
            });
        }
    }
    onDeleteAll = () => {
        const {updateDealerResourceLists} = this.state;
        const tmp = this.state.dealerResourceLists.map(v => Object.assign({}, v, {
            isUpdate: false
        }));
        this.setState({
            dealerResourceLists: [],
            updateDealerResourceLists: updateDealerResourceLists.concat(tmp),
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const {updateDealerResourceLists} = this.state;
        const dealerResourceLists = this.state.dealerResourceLists.filter(p => p.id !== id);
        const updateDealerResourceList = this.state.dealerResourceLists.filter(p => p.id === id);
        const tmp = updateDealerResourceList.map(v => Object.assign({}, v, {
            isUpdate: false
        }));
        this.setState({
            updateDealerResourceLists: updateDealerResourceLists.concat(tmp),
            dealerResourceLists,
            hasOperat: true
        });
    }
    onSelectDealerResourceLists = value => {
        const {data, updateDealerResourceLists} = this.state;
        const dealerResourceLists = this.state.dealerResourceLists;
        value.map(p => {
            const index = this.state.dealerResourceLists.findIndex(d => d.id === p.id);
            if(index === -1) {
                const detail = {
                    brandId: data.brandId,
                    id: p.id,
                    lV1Code: p.lV1Code,
                    lV1Name: p.lV1Name,
                    lV2Code: p.lV2Code,
                    lV2Name: p.lV2Name,
                    lV3Code: p.lV3Code,
                    lV3Name: p.lV3Name,
                    lV4Code: p.lV4Code,
                    lV4Name: p.lV4Name,
                    productCode: p.lv5Code,
                    productName: p.lv5Name,
                    isUpdate: true
                };
                dealerResourceLists.push(detail);
                updateDealerResourceLists.push(detail);
            }
            return p;
        });
        this.setState({
            showDealerResourceListSelectPanel: false,
            updateDealerResourceLists: [...updateDealerResourceLists],
            hasOperat: true,
            dealerResourceLists
        });
    }
    onSearch = () => {
        const {dealerResourceLists, lv2, lv3, lv4} = this.state;
        if(!dealerResourceLists.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'updatePanel.onClickSearchDetail.message',
                defaultMessage: '请先增加清单'
            }));
        if(lv2.length === 0 && lv3.length === 0 && lv4.length === 0) {
            this.setState({
                newDealerResourceLists: dealerResourceLists,
                isSearch: false,
            });
            return;
        }
        let lists = [];
        if(lv2.length > 0)
            lists = dealerResourceLists.filter(v => lv2.includes(v.lV2Code));
        if(lv3.length > 0)
            lists = dealerResourceLists.filter(v => lv3.includes(v.lV3Code));
        if(lv4.length > 0)
            lists = dealerResourceLists.filter(v => lv4.includes(v.lV4Code));
        this.setState({
            newDealerResourceLists: lists,
            isSearch: true
        });
    }
    onChangeCode = (value, name) => {
        this.setState({
            [name]: value
        });
    }
    onChangeDetail = (pagination, filters, sorter) => {
        this.setState({
            detailPagination: {
                pageIndex: pagination.current - 1,
                pageSize: pagination.pageSize,
                sortedColumnKey: sorter.columnKey,
                sortedOrder: sorter.order
            }
        });
    };
    render() {
        const {formatMessage} = this.props.intl;
        const {data, detailPagination, isSearch, newDealerResourceLists, dealerResourceLists, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1)
            data.brandId = brands[0].value;
        const columns = [{
            title: formatMessage({
                id: 'updatePanel.column.lV1Code',
                defaultMessage: '品牌编号'
            }),
            dataIndex: 'lV1Code',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV1Name',
                defaultMessage: '品牌名称'
            }),
            dataIndex: 'lV1Name',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV2Code',
                defaultMessage: '车型代码'
            }),
            dataIndex: 'lV2Code',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV2Name',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'lV2Name',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV3Code',
                defaultMessage: '版型'
            }),
            dataIndex: 'lV3Code',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV4Code',
                defaultMessage: '物料组'
            }),
            dataIndex: 'lV4Code',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.lV4Name',
                defaultMessage: '物料组名称'
            }),
            dataIndex: 'lV4Name',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.productCode',
                defaultMessage: '物料代码'
            }),
            dataIndex: 'productCode',
        }, {
            title: formatMessage({
                id: 'updatePanel.column.productName',
                defaultMessage: '物料名称'
            }),
            dataIndex: 'productName',
        }, {
            title: dealerResourceLists.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'updatePanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'updatePanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'updatePanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card className="form-standard" title={formatMessage({
                        id: 'updatePanel.column.common',
                        defaultMessage: '总代信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.name',
                                        defaultMessage: '名称'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.name}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.shortCode',
                                        defaultMessage: '简码'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.shortCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.shortName',
                                        defaultMessage: '简称'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.shortName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.agentKind',
                                        defaultMessage: '客户分类'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(agentKind, data.agentKind)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.country',
                                        defaultMessage: '国家'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.province',
                                        defaultMessage: '省份'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.province}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.city',
                                        defaultMessage: '城市'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.city}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.contactNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.fax',
                                        defaultMessage: '传真'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.fax}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.address',
                                        defaultMessage: '联系地址'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.address}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'updatePanel.operation.zipCode',
                                        defaultMessage: '邮政编码'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.zipCode}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={<div className="form-standard"><Row>
                            <Col span={4}>
                                {this.props.intl.formatMessage({
                                    id: 'updatePanel.operation.detail',
                                    defaultMessage: '可供资源清单'
                                })}
                            </Col></Row>
                        <Row><Col span={6}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'updatePanel.operation.lv2',
                                defaultMessage: '车型代码'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv2"
                                    value={this.state.lv2}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'updatePanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={6}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'updatePanel.operation.lv3',
                                defaultMessage: '版型'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv3"
                                    value={this.state.lv3}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'updatePanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'updatePanel.operation.lv4Code',
                                defaultMessage: '物料组'
                            })}
                            {...FORM_OPTIONS.item}>
                                <TextArea
                                    name="lv4"
                                    value={this.state.lv4}
                                    className={styles.minScreenSearchWidth}
                                    placeholder={formatMessage({
                                        id: 'updatePanel.form.placeholder',
                                        defaultMessage: '多个输入，以回车隔开'
                                    })}
                                    onBlur={this.onChangeCode}/>
                            </FormItem>
                        </Col>
                        <Col span={4}>
                            <Button key="query" type="primary" onClick={this.onSearch} loading={loading}>
                                {formatMessage({
                                    id: 'queryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}</Button></Col>
                        </Row></div>}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'updatePanel.btn.add',
                                    defaultMessage: '增加清单'
                                })}
                            </Button>
                            <Button
                                size="small"
                                onClick={this.onClickImportBtn}>
                                {formatMessage({
                                    id: 'newPanel.btn.import',
                                    defaultMessage: '导入清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={detailPagination}
                            onChange={this.onChangeDetail}
                            dataSource={isSearch ? newDealerResourceLists : dealerResourceLists}
                            {...TABLE} />
                            
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'updatePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {/* 导入清单弹出模态框 */}
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        brandId={data.brandId}
                        dealerId={data.id}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
                {/* 新增清单弹出模态框 */}
                {
                    this.state.showDealerResourceListSelectPanel && <DealerResourceListSelectPanel
                        dealerId={data.id}
                        brandId={data.brandId}
                        selectKey={dealerResourceLists.id}
                        onCancel={this.onClickAddDetailBtn}
                        onSelect={this.onSelectDealerResourceLists} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

UpdatePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryCondition,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
    
});
const mapDispatchToProps = (dispatch, props) => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(UpdatePanel));
